package com.studor.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.studor.common.Result;
import com.studor.entity.Questionnaire;
import com.studor.service.QuestionnaireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/questionnaire-report")
public class QuestionnaireReportController {

    @Autowired
    private QuestionnaireService questionnaireService;

    @GetMapping("/statistics")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Result<Map<String, Object>> getQuestionnaireStatistics() {
        List<Questionnaire> questionnaires = questionnaireService.list();

        if (questionnaires.isEmpty()) {
            return Result.success("暂无问卷数据");
        }

        Map<String, Object> statistics = new HashMap<>();

        // 基本统计
        statistics.put("totalCount", questionnaires.size());

        // 起床时间统计
        Map<String, Long> wakeTimeStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        q -> q.getWakeTime() + "点",
                        Collectors.counting()
                ));
        statistics.put("wakeTimeStats", wakeTimeStats);

        // 入睡时间统计
        Map<String, Long> sleepTimeStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        q -> {
                            int sleepTime = q.getSleepTime();
                            if (sleepTime == 25) return "1点";
                            return sleepTime + "点";
                        },
                        Collectors.counting()
                ));
        statistics.put("sleepTimeStats", sleepTimeStats);

        // 假期起床差异统计
        Map<String, Long> holidayDiffStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        q -> q.getHolidayDiff() + "小时",
                        Collectors.counting()
                ));
        statistics.put("holidayDiffStats", holidayDiffStats);

        // 打扫频率统计
        Map<String, Long> cleanFreqStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        q -> q.getCleanFreq() + "星",
                        Collectors.counting()
                ));
        statistics.put("cleanFreqStats", cleanFreqStats);

        // 整洁容忍度统计
        Map<String, Long> cleanToleranceStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        q -> {
                            int tolerance = q.getCleanTolerance();
                            if (tolerance <= 3) return "低(1-3分)";
                            if (tolerance <= 6) return "中(4-6分)";
                            return "高(7-10分)";
                        },
                        Collectors.counting()
                ));
        statistics.put("cleanToleranceStats", cleanToleranceStats);

        // 噪音介意统计
        Map<String, Long> studyNoiseStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        Questionnaire::getStudyNoise,
                        Collectors.counting()
                ));
        statistics.put("studyNoiseStats", studyNoiseStats);

        // 兴趣爱好统计
        Map<String, Long> hobbiesStats = new HashMap<>();
        questionnaires.forEach(q -> {
            if (q.getHobbies() != null && !q.getHobbies().isEmpty()) {
                String[] hobbies = q.getHobbies().split(",");
                for (String hobby : hobbies) {
                    hobbiesStats.merge(hobby.trim(), 1L, Long::sum);
                }
            }
        });
        statistics.put("hobbiesStats", hobbiesStats);

        // 上网频率统计
        Map<String, Long> netTimeStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        Questionnaire::getNetTime,
                        Collectors.counting()
                ));
        statistics.put("netTimeStats", netTimeStats);

        // 吸烟统计
        Map<String, Long> smokingStats = questionnaires.stream()
                .collect(Collectors.groupingBy(
                        Questionnaire::getSmoking,
                        Collectors.counting()
                ));
        statistics.put("smokingStats", smokingStats);

        // 平均值统计
        Map<String, Object> averages = new HashMap<>();
        averages.put("avgWakeTime", questionnaires.stream()
                .mapToInt(Questionnaire::getWakeTime)
                .average().orElse(0));
        averages.put("avgSleepTime", questionnaires.stream()
                .mapToInt(Questionnaire::getSleepTime)
                .average().orElse(0));
        averages.put("avgHolidayDiff", questionnaires.stream()
                .mapToDouble(q -> q.getHolidayDiff().doubleValue())
                .average().orElse(0));
        averages.put("avgCleanFreq", questionnaires.stream()
                .mapToInt(Questionnaire::getCleanFreq)
                .average().orElse(0));
        averages.put("avgCleanTolerance", questionnaires.stream()
                .mapToInt(Questionnaire::getCleanTolerance)
                .average().orElse(0));

        statistics.put("averages", averages);

        return Result.success(statistics);
    }

    @GetMapping("/detailed-list")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Result<List<Map<String, Object>>> getDetailedList() {
        List<Questionnaire> questionnaires = questionnaireService.list();

        List<Map<String, Object>> detailedList = questionnaires.stream().map(q -> {
            Map<String, Object> item = new HashMap<>();
            item.put("id", q.getId());
            item.put("wakeTime", q.getWakeTime() + "点");
            item.put("sleepTime", (q.getSleepTime() == 25 ? "1" : q.getSleepTime()) + "点");
            item.put("holidayDiff", q.getHolidayDiff() + "小时");
            item.put("cleanFreq", q.getCleanFreq() + "星");
            item.put("cleanTolerance", q.getCleanTolerance() + "分");
            item.put("studyNoise", q.getStudyNoise());
            item.put("hobbies", q.getHobbies());
            item.put("netTime", q.getNetTime());
            item.put("smoking", q.getSmoking());
            return item;
        }).collect(Collectors.toList());

        return Result.success(detailedList);
    }
}
